package org.vaillant.todo

class TaskService {

	static transactional = true

	def getCurrentsStatusHistoryByUser(User user,String filterTask){
		getCurrentStatusHistoryByUserAndStatusName(user,null, filterTask)
	}

	def finishTask(taskId){

		Task t = Task.get(taskId)

		Status finishStatus = Status.findByName('finish')

		StatusHistory st1 = new StatusHistory()
		t.addToStatus(st1)
		finishStatus.addToStatusHistory(st1)
	}

	def createNewTask(User user, String description){

		Task t = new Task(description:description).save()

		Status openStatus = Status.findByName('open')

		StatusHistory st1 = new StatusHistory()
		t.addToStatus(st1)
		openStatus.addToStatusHistory(st1)

		user.addToTasks(t)
	}

	/**
	 * Find all task with the same status for an user
	 * @param user
	 * @param nameStatus the status name to find
	 * @return list of {@link Task}
	 */
	def getCurrentStatusHistoryByUserAndStatusName(User user, String nameStatus, String filterTask) {

		def statusHistoryList = []

		def taskList

		if (!filterTask || filterTask == 'all'){
			taskList = Task.findAllByOwner(user,[sort:'dateCreated',order:'desc'])
		}else{

			def dateRef = new Date()
			dateRef.clearTime()
			if (filterTask == 'week'){
				dateRef = dateRef.minus(7)
			}else if (filterTask == 'month'){
				dateRef = dateRef.minus(30)
			}

			taskList = Task.findAllByDateCreatedGreaterThanEqualsAndOwner(dateRef,user,[sort:'dateCreated',order:'desc'])
		}


		taskList.each {
			def statusHistory = StatusHistory.findAllByTasks(it,[sort:'id',order:'desc'])[0]

			if (!nameStatus || statusHistory.status.name == nameStatus){
				statusHistoryList.add(statusHistory)
			}
		}

		return statusHistoryList
	}

	def sortStatusHistory(status, listOrder) {

		if (listOrder == 'desc'){
			status.sort { -it.status.id }
		}else{
			status.sort { it.status.id }
		}
	}
}
